<?php
/*Sql
 *  "RENAME TABLE `x6tm_cake-caddy_dev`.`posts`  TO `x6tm_cake-caddy_dev`.`pages` ;"
 *  "ALTER TABLE `pages` ADD `comments_count` INT( 10 ) NOT NULL DEFAULT '0';"
 *  "ALTER TABLE `pages` CHANGE `cat_id` `category_id` INT( 10 ) NOT NULL ; "
 *  "ALTER TABLE `pages` ADD `online` BOOL NOT NULL DEFAULT '0' AFTER `modified` ;"
 * 
 **/


class Page extends AppModel {
	var $name = 'Page';

	var $validate = array(
 					'title' => VALID_NOT_EMPTY,
 					'slug' => VALID_NOT_EMPTY,
 					'content' => VALID_NOT_EMPTY,
 					'online' => '`^[01]$`'
 					);
 					
 	var $belongsTo = array('User' => array(
 								'className' => 'User',
 								'conditions' => '',
 								'order' => '',
 								'foreignKey' => 'user_id'
 								),
 							'Category' => array(
 								'className' => 'Category',
 								'conditions' => '',
 								'order' => '',
 								'foreign_key' => 'category_id'
 								)
 							);
 							
 	var $hasMany = array('Comment' => array(
 								'className' => 'Comment',
 								'conditions' => '',
 								'order' => '',
 								'foreign_key' => 'page_id'
 								)
 							);
 							
 							
 	function validates(){
  			$this->__test_slug();
 			$this->__test_date();
	 		return count($this->invalidFields()) == 0;
	}
 	
 	function afterSave(){
 		$this->__category_pages_count();
	}
	
	function afterDelete(){
		//$this->__category_pages_count();
	}	
	
 	function __test_slug(){
		$slugs = $this->findBySlug($this->data['Page']['slug']);
		if (!empty($slugs) && $slugs['Page']['id'] != $this->id){
			//slug already taken
			$this->invalidate('slug', 'Slug is already used.');
			$this->set('slug_error', 'Slug already used');
		}
	}
	
	function __test_date(){
		if(!preg_match('`^[12][0-9]{3}-[0-9]{2}-[0-9]{2} ([0-9]{2}:){2}[0-9]{2}$`', $this->data['Page']['created'])){
			//invalid date : set to today
			$this->data['Page']['created'] = date('Y-m-d H:i:s');
		}
	}
	
	function __category_pages_count(){
		if(!empty($this->data['Page']['category_id'])){
			$pages_count = $this->findCount(array('category_id' => $this->data['Page']['category_id'], 'online' => '1'));
			$this->Category->id = $this->data['Page']['category_id'];
			$this->Category->saveField('pages_count', $pages_count);
		}
	}
	
}
?>
